package com.dou.you.che.service.impl.sys;

import com.alibaba.fastjson.JSON;
import com.dou.you.che.comm.utils.IdUtil;
import com.dou.you.che.comm.utils.exception.WebException;
import com.dou.you.che.core.entity.sys.SysConfig;
import com.dou.you.che.core.mapper.sys.SysConfigDao;
import com.dou.you.che.service.sys.SysConfigServiceI;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * 系统配置信息
 * @Author 黄国刚【1058118328@qq.com】
 */
@Service
@Transactional(readOnly = true)
public class SysConfigService implements SysConfigServiceI{

    @Autowired
    private SysConfigDao sysConfigDao;

    @Transactional(readOnly = false)
    @Override
    public void save(SysConfig config) {
        config.setId(IdUtil.createIdbyUUID());
        config.setStatus(1);
        sysConfigDao.save(config);
    }

    @Transactional(readOnly = false)
    @Override
    public void update(SysConfig config) {
        sysConfigDao.update(config);
    }

    @Transactional(readOnly = false)
    @Override
    public void updateValueByKey(String key, String value) {
        sysConfigDao.updateValueByKey(key, value);
    }

    @Transactional(readOnly = false)
    @Override
    public void deleteBatch(String[] ids) {
        sysConfigDao.deleteBatch(ids);
    }

    @Override
    public List<SysConfig> queryList(Map<String, Object> map) {
        return sysConfigDao.queryList(map);
    }

    @Override
    public int queryTotal(Map<String, Object> map) {
        return sysConfigDao.queryTotal(map);
    }

    @Override
    public SysConfig queryObject(String id) {
        return sysConfigDao.queryObject(id);
    }

    @Override
    public String getValue(String key, String defaultValue) {
        String value = sysConfigDao.queryByKey(key);
        if(StringUtils.isBlank(value)){
            return defaultValue;
        }
        return value;
    }

    @Override
    public <T> T getConfigObject(String key, Class<T> clazz) {
        String value = getValue(key, null);
        if(StringUtils.isNotBlank(value)){
            return JSON.parseObject(value, clazz);
        }

        try {
            return clazz.newInstance();
        } catch (Exception e) {
            throw new WebException("获取参数失败");
        }
    }
}
